package com.jyk.zcube.controller;

import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.jyk.zcube.common.CommonLogText;
import com.jyk.zcube.dao.TestUserMapper;
import com.jyk.zcube.model.TestUser;
import com.jyk.zcube.model.TestUserExample;

@Controller
public class BoardHomeController {
	
	private static final Logger logger = LoggerFactory.getLogger(BoardHomeController.class);
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@SuppressWarnings("null")
	@RequestMapping(value = "/board", method = RequestMethod.GET)
	public String boardHome(Locale locale, Model model) {
		
		logger.info(CommonLogText.logMethodStart + "boardHome Method");
		logger.info("Welcome home! the client locale is "+ locale.toString());
		
		String resource = "com/jyk/zcube/mybatis-config.xml";
		InputStream inputStream;
		SqlSessionFactoryBuilder builder;
		SqlSessionFactory factory;
		TestUserMapper testUserMapper = null;
		TestUser testUser = null;
		TestUserExample testUserExample = null;
		List<TestUser> testUserList = null;
		
		try {
			inputStream = Resources.getResourceAsStream(resource);
			builder = new SqlSessionFactoryBuilder();
			factory = builder.build(inputStream);
			
			factory.openSession();
			
			testUserExample = new TestUserExample();
			
			TestUserExample.Criteria testUserCriteria = testUserExample.createCriteria();
			
			testUserCriteria.andIdEqualTo("TU_111");
			
			testUserList = testUserMapper.selectByExample(testUserExample);
			
			for(int i=0; i<testUserList.size(); i++){
				
				testUser = testUserList.get(i);
				
				model.addAttribute("id" + Integer.toString(i), testUser.getId());
				model.addAttribute("name" + Integer.toString(i), testUser.getName());
				model.addAttribute("age" + Integer.toString(i), testUser.getAge());
				model.addAttribute("create_date" + Integer.toString(i), testUser.getCreateDate());
				
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Date date = new Date();
		DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
		
		String formattedDate = dateFormat.format(date);
		
		model.addAttribute("serverTime", formattedDate);
		
		logger.info(CommonLogText.logMethodEnd + "boardHome Method");
		
		return "BoardHome";
	}

}
